summaryrefslogtreecommitdiff
path: root/app/src/routes/assignments/[assignmentId]/+page.server.ts
blob: 280c5bd0dd1b41500cca02e58c216482a25c84da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { finishAssignment, getAssignmentAndCemetaryById } from "$lib/server/assignments";
import type { PageServerLoad, Actions } from "./$types";
import { error, redirect } from "@sveltejs/kit";

export const load = (async ({ params, url, locals }) => {
	if (!locals.user) {
		redirect(303, `/login?redirectTo=${encodeURIComponent(url.toString())}`);
	}

	const { assignment, cemetaryPlot } = await getAssignmentAndCemetaryById(
		locals.dbConn,
		+params.assignmentId,
	);
	if (!assignment) {
		return error(404, `Cemetary plot with id ${params.assignmentId} not found`);
	}
	console.debug("Found assignment: ", assignment);
	if (assignment.gardenerId !== locals.user.id) {
		return error(403, "This assignment isn't for you!");
	}

	return {
		user: locals.user,
		assignment,
		cemetaryPlot,
	};
}) satisfies PageServerLoad;

export const actions = {
	// FIXME: Skipped input validation.
	// FIXME: Is 'load' action run (wrt. authentication)?
	finish: async ({ params, request, locals }) => {
		const formData = await request.formData();
		const imageFiles = formData.getAll("images") as File[];
		const note = (formData.get("note") as string | null) ?? undefined;

		// Read image files in parallel.
		const images = await Promise.all(
			imageFiles.map(async (f) => ({
				name: f.name,
				bytes: new Uint8Array(await f.arrayBuffer()),
			})),
		);

		await finishAssignment(locals.dbConn, locals.s3Client, {
			images,
			note,
			assignmentId: +params.assignmentId, // We have parsing at home...
		});

		return { success: true };
	},
} satisfies Actions;